package com.yhx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhx.iservice.IOrderService;
import com.yhx.mapper.MemberMapper;
import com.yhx.mapper.OrderMapper;
import com.yhx.mapper.OrdersettingMapper;
import com.yhx.pojo.*;
import com.yhx.utils.DateUtils;
import com.yhx.utils.MessageConstant;
import com.yhx.utils.Result;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IOrderServiceImpl implements IOrderService {
    //体检预约方法处理逻辑比较复杂，需要进行如下业务处理：
    //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行 预约
    //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
    //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
    //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注 册并进行预约
    //5、预约成功，更新当日的已预约人数
    @Resource
    private OrdersettingMapper ordersettingMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private OrderMapper orderMapper;

    @Override
    public Result doOrder(OrderBo orderBo) throws ParseException {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行 预约
        QueryWrapper<Ordersetting> ordersettingQueryWrapper = new QueryWrapper<>();
        ordersettingQueryWrapper.eq("orderDate", orderBo.getOrderDate());
        Ordersetting ordersetting = ordersettingMapper.selectOne(ordersettingQueryWrapper);
        //如果没有设置
        if (ordersetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        if (ordersetting.getNumber() - ordersetting.getReservations() <= 0) {
            //已经约满了
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3，没有约满
        // 检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注 册并进行预约
        //判断手机号在会员表中是否存在
        QueryWrapper<Member> memberQueryWrapper = new QueryWrapper<>();
        memberQueryWrapper.eq("phoneNumber", orderBo.getTelephone());
        Member member = memberMapper.selectOne(memberQueryWrapper);
        if (member == null) {
            //不是会员
            member = new Member();
            member.setRegtime(new Date());
            member.setPhonenumber(orderBo.getTelephone());
            member.setIdcard(orderBo.getIdCard());
            member.setName(orderBo.getName());
            member.setSex(orderBo.getSex() == 1 ? "男" : "女");
            member.setPassword("123456");
            member.setBirthday(getBirthdayFromIdCard(orderBo.getIdCard()));
            memberMapper.insert(member);//执行添加之后，mybatisplus自动把id查出来
        }
        //现在一定是会员了
        //检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约 则无法完成再次预约
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("member_id", member.getId())
                .eq("orderDate", orderBo.getOrderDate())
                .eq("setmeal_id", orderBo.getSetmealId());
        Order order = orderMapper.selectOne(orderQueryWrapper);
        if (order != null) {
            //同一个用户在同一天已经预约过了该项目
            return new Result(false, MessageConstant.HAS_ORDERED);
        }
        //进行预约
        Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(orderBo.getOrderDate());
        Order order1 = new Order(0, member.getId(), parse, "微信公众号预约", "未到诊", orderBo.getSetmealId());
        int insert = orderMapper.insert(order1);
        if (insert == 0) {
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
        //5、预约成功，更新当日的已预约人数
        ordersetting.setReservations(ordersetting.getReservations() + 1);
        int i = ordersettingMapper.updateById(ordersetting);
        if (i == 0) {
            return new Result(false, MessageConstant.ORDER_FAIL);
        }
        return new Result(true, MessageConstant.ORDER_SUCCESS);

    }

    @Override
    public Long getTodayOrderNumber() {
        try {
            //今天
            String s = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("orderDate", s);
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Long getTodayVisitsNumber() {
        try {
            //今天到诊
            String s = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("orderDate", s).eq("orderStatus", "已到诊");
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Long getThisWeekOrderNumber() {
        try {
            //今天
            String today = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            //本周1
            String monday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.between("orderDate", monday, today);
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Long getThisWeekVisitsNumber() {
        //本周到诊
        try {
            //今天
            String today = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            //本周1
            String monday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.between("orderDate", monday, today).eq("orderStatus", "已到诊");
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Long getThisMonthOrderNumber() {
        try {
            //今天
            String today = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            //本周1
            String monday = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.between("orderDate", monday, today);
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public Long getThisMonthVisitsNumber() {
        try {
            //今天
            String monday = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth(), "yyyy-MM-dd");
            //本周1
            String today = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.between("orderDate", monday, today).eq("orderStatus", "已到诊");
            return orderMapper.selectCount(orderQueryWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }

    @Override
    public List<OrderInfo> pagelist(String name, String tel, String date, int pageNum, int pageSize) {
        int num = (pageNum - 1) * pageSize;
        List<OrderInfo> orderInfos = orderMapper.pageLiat(name, tel, date, num, pageSize);
        return orderInfos;
    }

    @Override
    public Long currentPage(String name, String tel, String date) {
        Long aLong = orderMapper.currentPage(name, tel, date);
        return aLong;
    }

    @Override
    public Result orderByTime(String activeName, int pageNum, int pageSize) {
        if (activeName == null) {
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
        List<String> startANDEndTime = getStartANDEndTime(activeName);
        String startTime = startANDEndTime.get(0);
        String endTime = startANDEndTime.get(1);
        int num = (pageNum - 1) * pageSize;
        List<OrderInfo> orderInfos = orderMapper.orderByTime(startTime, endTime, num, pageSize);
        if (orderInfos == null || orderInfos.size() == 0) {
            return new Result(false, "数据为空或者查询失败");
        }
        Long aLong = orderMapper.totalTime(startTime, endTime);
        return new Result(true, "查询成功", orderInfos,aLong);
    }

    @Override
    public Result pageList(String activeName, String name, String tel, String date, int pageNum, int pageSize) {
        if (activeName == null) {
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
        List<String> startANDEndTime = getStartANDEndTime(activeName);
        String startTime = startANDEndTime.get(0);
        String endTime = startANDEndTime.get(1);
        int num = (pageNum - 1) * pageSize;
        List<OrderInfo> orderInfos = orderMapper.pageList(name, tel, date, startTime, endTime, num, pageSize);
        Long total = orderMapper.total(startTime, endTime, name, tel, date);
        return new Result(true, "查询成功",orderInfos,total);
    }

    @Override
    public Order getByid(int id) {
        return orderMapper.selectById(id);
    }

    @Override
    public Result update(Order order) {
        if(order.getOrderstatus().equals("已到诊")){
            return new Result(false, "已经是到诊状态，请不要重复确认");
        }
        order.setOrderstatus("已到诊");
        int update = orderMapper.updateById(order);
        if(update>0){
            return new Result(true,"修改状态成功");
        }
        return new Result(false, "修改状态失败");
    }

    private List<String> getStartANDEndTime(String activeName) {
        List<String> list = new ArrayList<>();
        switch (activeName) {
            case "first":
                try {
                    //全部会员信息
                    list.add("2000-01-01");
                    list.add("2050-12-31");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "second":
                try {
                    //今天预约的会员信息
                    list.add(DateUtils.parseDate2String(new Date(), "yyyy-MM-dd"));
                    list.add(DateUtils.parseDate2String(new Date(), "yyyy-MM-dd"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "third":
                try {
                    //本周预约的会员信息
                    String startTime = DateUtils.parseDate2String(DateUtils.getThisWeekMonday(), "yyyy-MM-dd");
                    String endTime = DateUtils.parseDate2String(DateUtils.getSundayOfThisWeek(), "yyyy-MM-dd");
                    list.add(startTime);
                    list.add(endTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "fourth":
                try {
                    //这个月预约的会员信息
                    String startTime = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth(), "yyyy-MM-dd");
                    //2020-02-20
                    String substring = startTime.substring(0, 7);
                    String endTime = substring + "-31";
                    list.add(startTime);
                    list.add(endTime);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
        return list;
    }






    /**
     * 从身份证获取生日
     * @param idCard 身份证
     * @return 生日
     */
    private Date getBirthdayFromIdCard(String idCard){
        String time = idCard.substring(6, 14);
        try {
            Date date = new SimpleDateFormat("yyyyMMdd").parse(time);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
